<?php
class MY_Controller extends CI_Controller {
	public $accept = 'html';
	public $template;
	public $assign;
	public $tempDir = "";
	public $curUser = null;
	public $configure = array();
	
	/**
		var $beforeFilter = array(
			'method' =>array(
				'only' => array(),
				'except'  => array(),
			),	
		);
		or
		var $beforeFilter = array( 'method1','method2' )
	*/
	var $beforeFilter = array();

	public function MY_Controller(){
		parent::__construct();
		if(isset($_GET['debug'])){
			error_reporting(2047);
		}else{
			error_reporting(1);
		}
		$this->config->load('system');
		$accept = isset( $_REQUEST['accept'] ) ? strtolower( $_REQUEST['accept'] ) : 'html';
		$this->accept = $accept;
		
		if(isset($_REQUEST['template'])){
			$this->template = $_REQUEST['template'];
		}else{
			global $class,$method;
			$this->template = $class."_".$method;
		}

		//加载系统配置
		$cacheFile = realpath(APPPATH).'/tmp/~configure.php';
		if(file_exists($cacheFile)){
			$_configure = include($cacheFile);
		}else{
			$this->load->model('Config');
			$rs = $this->Config->doList();
			foreach($rs as $_rs){
				$_configure[$_rs['code']] = $_rs['value'];
			}
			$content = 'return '.var_export( $_configure,true ).";\n";
			$content  = "<?php\n".$content."\n?>";
			file_put_contents( $cacheFile,$content );
		}
		$this->configure = $_configure;
		$this->doBeforeFiter();
	}
	
	//执行前置过滤函数和方法
	public function doBeforeFiter(){
		if(empty($this->beforeFilter)){
			return;
		}
		global $method;
		$actionArray = array();
		foreach($this->beforeFilter as $action=>$setting){
			if(is_string($setting)){
				$actionArray[] = $setting;
			}else{
				if(isset($setting['except'])){
					if(!in_array($method,$setting['except'])){
						$actionArray[] = $action;
					}
					continue;
				}else if(isset($setting['only'])){
					if(in_array($method,$setting['only'])){
						$actionArray[] = $action;
					}
					continue;
				}else{
					$actionArray[] = $action;
				}
			}
		}
		if(!empty($actionArray)){
			foreach($actionArray as $action){
				$this->doRun($action);
			}
		}
	}

	public function validation($rules,$model=null){
		$this->form_validation->set_rules($rules);
		if($model!=null){
			$fields = $model;
			if(is_string($model)){
				$this->lang->load('model');
				$fields = $this->lang->line("val_".$model);
			}
			$this->form_validation->set_rules($fields);
		}
		return $this->form_validation->run();
	}


	/**
     +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
     +----------------------------------------------------------
     * @access protected 
     +----------------------------------------------------------
     * @param string $name 数据对象名称 
     +----------------------------------------------------------
     * @return HashMap
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    protected function _searchWhere($model) 
    {
		$map	=	array();
        foreach($model->_field as $key=>$val) {
            if(isset($_REQUEST[$key]) && $_REQUEST[$key]!='' && $_REQUEST[$key]!='-100') {
                $map[$key]	=	$_REQUEST[$key];
            }
        }
        return $map;
    }

	protected function _searchLike($model,$sfield=null,$keyword=null){	
		$sfield = empty($sfield)?$_REQUEST['sfield']:$sfield;
		$keyword = empty($keyword)?$_REQUEST['keyword']:$keyword;
		if(empty($sfield)||empty($keyword)) return null;
		if(is_string($sfield)) $sfield = explode(',',$sfield);
		$like = array();
		foreach($sfield as $f){
			if($f==$model->_prkey){
				$_REQUEST[$model->_prkey] = $keyword;
				continue;
			}
			$like[$f] = $keyword;
		}
		return $like;
	}

	/**
     +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
     +----------------------------------------------------------
     * @access protected 
     +----------------------------------------------------------
     * @param Model $model 数据对象 
     * @param HashMap $map 过滤条件 
     * @param string $sortBy 排序 
     * @param boolean $asc 是否正序 
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    /**
     * 根据表单生成查询条件
     * 进行列表过滤
	 *
     * @access protected 
     * @param Model $model 数据对象 
     * @param HashMap $map 过滤条件 
     * @param string $sortBy 排序 
     * @param boolean $asc 是否正序 
     * @return void
     * @throws KoExecption
     */
    protected function _list($model,$map,$join=null,$field='*',$isQuery=true,$sortBy='id',$asc=true) 
    {
        //排序字段 默认为主键名
		$rs = array();
        if(isset($_REQUEST['order'])) {
            $order = $_REQUEST['order'];
        }else {
            $order = $sortBy;
        }
		$order = !empty($order)? $order: $model->_prkey;

        //排序方式默认按照倒序排列
        //接受 sost参数 0 表示倒序 非0都 表示正序
        if(isset($_REQUEST['sort'])) {
            $sort = $_REQUEST['sort']?'asc':'desc';
        }else {
            $sort = $asc?'asc':'desc';
        }
        //取得满足条件的记录数
		$model = $this->_pagecond($model,$map);
		$db = clone $model->db;
		$count = $db->count_all_results($model->_table);
		unset($db);
		if($count>0) {
			$this->load->library('pagination');
			$data = $_REQUEST;
			$param = $data;
			unset($param['per_page']);
			unset($param['ci_session']);
			$config = $this->config->item('system_pager_cfg');

			//动态设置pagesize
			if(isset($_GET['pagesize'])&&intval(&$_GET['pagesize'])>0){
				$config['per_page'] = $_GET['pagesize'];
			}

			$config['base_url'] = base_url().$_SERVER['PHP_SELF']."?".http_build_query($param);
			$config['total_rows'] = $count;
			$config['page_query_string'] = true;
			$this->pagination->initialize($config);
			$num 				= $config['per_page'];
			$offset 			= $data['per_page'];
			if($isQuery){
				if(!empty($join)){
					$this->db->join($join['table'],$join['on']);
				}
				$this->db->select($field);
				$query 	= $model->db->order_by($order, $sort)->get($model->_table,$num, $offset);
				$rs['resultset']	= $query->result_array();
			}else{
				$rs['resultset']	= null;
				$rs['model']		= $model;
			}
			$rs['order']		= $order;
			$rs['sort']			= $sort;
			$rs['num']			= $num;
			$rs['offset']		= $offset;
			$rs['pager']		= $this->pagination;
			$rs['param']		= $param;
		}
        return $rs;
    }
 
 
	private function _pagecond($model,$map){
		if(!empty($map)){
			if(is_string(key($map))){
				foreach($map as $key=>$val){
					$model->db->$key($val);
				}
			}else{
				$model->db->where($map);
			}
		}
		return $model;
	}
	
	//运行一个方法或者函数
	protected function doRun($action){
		//动作存在
		if( method_exists( $this,$action ) ){
			//执行操作
			$this->$action();
		}elseif(function_exists($action)){
			$action();
		}else{//不存在
			$this->__empty();
		}
	}

	//空的方法
	protected function __empty(){

	}

	protected function initAdmin(){
		$this->tempDir = "admin/";
		$redirect = $_SERVER['REQUEST_URI'];
		$redirect = site_url('admin/login/?redirect='.urlencode($redirect));
		//如果成功登陆了
		if($this->authorize($redirect)){
			return true;
			$this->showMessage('Permission denied',$redirect);
		}
	}

	protected function authorize($loginUrl=null){
		if($this->session->userdata('id')){
			$this->curUser = array(
				'id' => $this->session->userdata('id'),
				'username' => $this->session->userdata('username'),
				'truename' => $this->session->userdata('truename'),
			);
		}
		if($loginUrl==null) $loginUrl = $this->config->item('system_login_url');
		if(empty($this->curUser)){
			$this->load->helper('url');
			redirect($loginUrl, 'refresh');
		}
		return true;
	}

	protected function _init(){
		//加载导航
		$this->assign['_nav_guide'] = $this->loadNav();
	}

	//加载导航
	function loadNav(){
		$cacheFile = realpath(APPPATH).'/tmp/~nav.php';
		if(file_exists($cacheFile)&&!$_GET['rebuild']){
			$nav = include($cacheFile);
		}else{
			$this->load->model('Nav');
			$rs = $this->Nav->listNav(null,array('is_show'=>1));
			$rs = cat_options(0, $rs);
			$nav = array();
			foreach($rs as $_rs){
				$nav[$_rs['position']][] = $_rs;
			}
			$content = 'return '.var_export( $nav,true ).";\n";
			$content  = "<?php\n".$content."\n?>";
			file_put_contents( $cacheFile,$content );
		}
		return $nav;
	}

	public function showMessage($mesCode,$redirect=null){
		$div = "\n";
		$message = $this->lang->line($mesCode);
		if(empty($message)) $message = $mesCode;
		switch( $this->accept ){
			case 'html':
				$data['message'] = $message;
				$data['redirct'] = $redirect;
				$message_temp = $this->config->item('system_message_temp');
				include($message_temp);
				break;
			case 'js':
				$div = "[js]";
			default:
				$data['message'] = $message;
				$data['redirct'] = $redirect;
				echo implode( $div,$data );
				echo( $div ."\n" );
				break;
		}
		exit();
	}

	/**
	 * 取得跳转链接
	 *
	 * @param string $defaultUrl 默认跳转页面
	 * @return string
	 */
	public function getRedirect( $defaultUrl = 'index.php'  ){
		if(isset($_REQUEST['redirect'])&&!empty($_REQUEST['redirect'])){
			$redirect = trim( $_REQUEST['redirect'] );
		}else{
			$url = $this->lang->line($defaultUrl);
			if(!empty($url)) $defaultUrl = $url;
			$redirect = $defaultUrl;
		}
		$redirect = rawurldecode( $redirect );
		return $redirect;
	}

	/**
	*	返回当前或者前一个页面的链接
	*	@author	kokko<kokko313@gmail.com>
	*	@version 1.0 2007-8-30
	*	@param $current
	*	@return String
	*/
	function get_returnurl( $current = true ){
		if( isset( $_SERVER['HTTP_REFERER'] ) && !$current ){
			$url = $_SERVER['HTTP_REFERER'];
		}else{
			$url = $_SERVER['REQUEST_URI'];
		}
		return  $url;
	}

	public function display($data=null,$temp=null){
		$temp = empty($temp)? $this->template : $temp;
		if($this->accept!='html') $temp = $this->accept."/".$temp;
		$data = empty($data)? $this->assign : $data;
		$this->load->view($this->tempDir.$temp,$data);
	}

	/**
     * 加载模型
	 *
     * @access protected 
     * @param string $name 数据对象名称 
     * @return void
     * @throws KoExecption
     */
	protected function _loadModel($name){
		$this->load->model($name);
		//如果没有字段就初始化
		if(empty($this->$name->_field)){
			$this->$name->init();
		}
	}
}